<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 提示区 -->
      <el-alert
        title="添加商品信息"
        type="info"
        :closable="false"
        show-icon
        center
      >
      </el-alert>
      <!-- 步骤条 -->
      <el-steps
        :space="200"
        :active="activeIndex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tab区域 -->
      <el-form
        :model="addGoodsForm"
        :rules="addGoodsRules"
        ref="addGoodsRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          :tab-position="'left'"
          style="height: 100%"
          v-model="activeIndex"
          :before-leave="beforeTabLeave"
          @tab-click="tabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input
                v-model="addGoodsForm.goods_price"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input
                v-model="addGoodsForm.goods_number"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input
                v-model="addGoodsForm.goods_weight"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                expand-trigger="hover"
                :options="parentCateList"
                :props="parentCateProps"
                v-model="addGoodsForm.goods_cat"
                @change="parentCateChanged"
              >
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTabData"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="vals"
                  v-for="(vals, i) in item.attr_vals"
                  :key="i"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTabData"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- action标识图片要上传到的后台api地址 -->
            <el-upload
              :action="uploadUrl"
              :on-preview="uploadPreview"
              :on-remove="uploadRemove"
              :on-success="uploadSuccess"
              list-type="picture"
              :headers="headerObj"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor
              v-model="addGoodsForm.goods_introduce"
              ref="myQuillEditor"
              :options="editorOption"
            >
            </quill-editor>
            <!-- 添加商品 -->
            <el-button type="primary" class="btnAdd" @click="addGoods"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 预览图片对话框 -->
    <el-dialog
      title="图片预览"
      :visible.sync="preview_dialogVisible"
      width="30%"
    >
      <img :src="previewUrl" alt="" class="previewImg" />
    </el-dialog>
  </div>
</template>
<script>
import _ from 'lodash'
export default {
  data() {
    return {
      activeIndex: '0',
      addGoodsForm: {
        goods_name: '',
        goods_price: '',
        goods_number: '',
        goods_weight: '',
        goods_introduce: '',
        goods_cat: [],
        pics: [],
        attrs: [],
      },
      addGoodsRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
        ],
      },
      //  父级分类列表
      parentCateList: [],
      // 级联选择器的配置属性
      parentCateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      manyTabData: [],
      onlyTabData: [],
      //   上传图片的url
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      //   图片上传组件的header请求头
      headerObj: {
        Authorization: window.sessionStorage.getItem('token'),
      },
      previewUrl: '',
      preview_dialogVisible: false,
      editorOption: {},
    }
  },
  created() {
    this.getParentCateList()
  },
  methods: {
    // 获取商品分类数据
    async getParentCateList() {
      const { data: res } = await this.$http.get('categories')
      //   console.log(res)
      if (res.meta.status !== 200)
        return this.$message.error('获取父级分类失败')
      this.parentCateList = res.data
    },
    // 商品父级分类的改变
    parentCateChanged() {
      if (this.addGoodsForm.goods_cat.length !== 3) {
        this.addGoodsForm.goods_cat = []
        return
      }
    },
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addGoodsForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类')
        return false
      }
    },
    //
    async tabClick() {
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'many' },
          }
        )
        // console.log(res)
        if (res.meta.status !== 200)
          return this.$message.error('获取动态参数项失败')
        res.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyTabData = res.data
      } else if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'only' },
          }
        )
        console.log(res)
        if (res.meta.status !== 200)
          return this.$message.error('获取动态参数项失败')
        // res.data.forEach((item) => {
        //   item.attr_vals =
        //     item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        // })
        this.onlyTabData = res.data
      }
    },
    // 处理图片预览效果
    uploadPreview(file) {
      this.previewUrl = file.response.data.url
      this.preview_dialogVisible = true
    },
    // 处理移除图片的操作
    uploadRemove(file) {
      // 需要删除的url
      const removUrl = file.response.data.tmp_path
      const index = this.addGoodsForm.pics.findIndex((x) => x.pic === removUrl)
      this.addGoodsForm.pics.splice(index, 1)
    },
    // 监听图片上传成功的事件
    uploadSuccess(res) {
      // if(res.data.status!==200) return this.$message.error("上传失败")
      // 1.拼接得到图片信息对象
      const picInfo = { pic: res.data.tmp_path }
      // 2.将图片对象push到pics数组中
      this.addGoodsForm.pics.push(picInfo)
      // console.log( this.addGoodsForm);
    },
    // 添加商品
    addGoods() {
      // console.log(this.addGoodsForm)
      this.$refs.addGoodsRef.validate(async (data) => {
        if (!data) return this.$message.error('请填写必要的表单项')
        // 执行添加到请求
        const form = _.cloneDeep(this.addGoodsForm)
        // 拼接成字符串
       form.goods_cat = form.goods_cat.join(',')
        // 处理动态参数
        this.manyTabData.forEach((item) => {
          const attrsInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' '),
          }
          this.addGoodsForm.attrs.push(attrsInfo)
        })
        // 处理静态属性
        this.onlyTabData.forEach((item) => {
          const attrsInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          }
          this.addGoodsForm.attrs.push(attrsInfo)
        })
        form.attrs = this.addGoodsForm.attrs
        // 发起请求,商品名称是唯一的
        const { data: res } = await this.$http.post('goods', form)
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error('添加商品失败')
        this.$message.success('添加商品成功')
        this.$router.push('/goods')
      })
    },
  },
  computed: {
    cateId() {
      if (this.addGoodsForm.goods_cat.length === 3) {
        return this.addGoodsForm.goods_cat[2]
      }
      return null
    },
  },
}
</script>
<style lang="less" scoped>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.el-upload__tip {
  font-size: 13px;
}
.previewImg {
  width: 100%;
}
.btnAdd {
  margin-top: 15px;
}
</style>